import { TaskSessionRepository } from '../repositories';
import { ITaskSession, ISubTask } from '../models/types';
import mongoose from 'mongoose';

export class TaskSessionService {
  private taskSessionRepository: TaskSessionRepository;

  constructor(taskSessionRepository: TaskSessionRepository) {
    this.taskSessionRepository = taskSessionRepository;
  }

  async createTaskSession(sessionData: Partial<ITaskSession>): Promise<ITaskSession> {
    // Add any business logic here, e.g., validation, setting defaults
    return this.taskSessionRepository.create(sessionData);
  }

  async getTaskSession(sessionId: string): Promise<ITaskSession | null> {
    return this.taskSessionRepository.findById(sessionId);
  }

  async updateTaskSessionStatus(sessionId: string, status: ITaskSession['status'], userId: string): Promise<ITaskSession | null> {
    // Add business logic, e.g., checking permissions
    return this.taskSessionRepository.updateStatus(sessionId, status, userId);
  }

  async addSubTaskToSession(sessionId: string, subTaskData: Omit<ISubTask, 'subTaskId' | 'createdAt' | 'updatedAt'>): Promise<ITaskSession | null> {
    // Business logic for adding a subtask
    return this.taskSessionRepository.addSubTask(sessionId, subTaskData);
  }

  // Example of a method that uses a transaction
  async createMessageAndUpdateSession(messageData: any) {
    const session = await mongoose.startSession();
    session.startTransaction();
    try {
      // This is a placeholder for creating a message
      // const newMessage = new Message(messageData);
      // await newMessage.save({ session });

      await this.taskSessionRepository.incrementMessageCount(messageData.sessionId, new Date());

      await session.commitTransaction();
    } catch (error) {
      await session.abortTransaction();
      throw error;
    } finally {
      session.endSession();
    }
  }
}
